package com.kummuna.ui;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Session;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kummuna.R;
import com.kummuna.config.MainConfiguration;
import com.kummuna.util.image.ImageLoader;
import com.kummuna.util.json.JSONParser;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.util.Log;
import android.content.res.Resources.NotFoundException;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Detectivemap extends Activity implements LocationListener {

	GoogleMap map;
	MapView mapView;
	ArrayList<LatLng> markerPoints;
	private String distance;
	private String duration;
	private Location locationPresent;
	private String latitudeFormAddWaterLeak;
	private String longtitudeFormAddWaterLeak;
	private String topicFormAddWaterLeak;
	private String detailFormAddWaterLeak;
	private String timeFormAddWaterLeak;
	private String statusFormAddWaterLeak;
	private String urlFormAddWaterLeak;
	private String location;
	private String Id;
	private String flagAutan;
	private static String url;
	public ArrayList<HashMap<String, String>> result;

	public static final String TAG_ID = "Id";
	public static final String TAG_LatPoint = "LatPoint";
	public static final String TAG_LongPoint = "LongPoint";
	public static final String TAG_Status = "Status";
	public static final String TAG_UserId = "UserId";
	public static final String TAG_Topic = "Topic";
	public static final String TAG_Detail = "Detail";
	public static final String TAG_Date = "Date";
	public static final String TAG_State = "State";
	public static final String TAG_Url = "Url";
	
	public ImageLoader imageLoader;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detectivemap);

		markerPoints = new ArrayList<LatLng>();

//		Log.d("id", ModelLogIn.id);
//		Log.d("name", ModelLogIn.name);
//		Log.d("url", ModelLogIn.image);
		setUpMapIfNeeded();
		setUpLocation();
		setUpMarker();
		setUpBounds();
		map.setInfoWindowAdapter(new InfoWindowAdapter() {

			@Override
			public View getInfoWindow(Marker arg0) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public View getInfoContents(Marker arg0) {
				// Getting view from the layout file info_window_layout
				View v = getLayoutInflater()
						.inflate(R.layout.info_window, null);
				
				
		        imageLoader=new ImageLoader(Detectivemap.this.getApplicationContext());

				// Getting the position from the marker
//				LatLng latLng = arg0.getPosition();

		        ImageView thumb_image=(ImageView)v.findViewById(R.id.picture_Info);
				TextView tv_Topic = (TextView) v.findViewById(R.id.tv_topic);
				TextView tv_Date = (TextView) v.findViewById(R.id.tv_date);
				TextView tv_Detail = (TextView) v.findViewById(R.id.tv_detail);
				TextView tv_State = (TextView) v.findViewById(R.id.tv_status);
				TextView tv_Location = (TextView) v.findViewById(R.id.tv_location);
				
				imageLoader.DisplayImage(urlFormAddWaterLeak, thumb_image);

				// Getting reference to the TextView to set topic
				// tv_Topic.setText("" + latLng.latitude);
				tv_Topic.setText(topicFormAddWaterLeak);
				// Getting reference to the TextView to set date
				tv_Date.setText(timeFormAddWaterLeak);
				// Getting reference to the TextView to set detail
				tv_Detail.setText(detailFormAddWaterLeak);
				// Getting reference to the TextView to set status
				tv_State.setText(Id);
				// Getting reference to the TextView to set location
				tv_Location.setText(location);

				// Returning the view containing InfoWindow contents
				return v;

			}
		});
		
		map.setOnMarkerClickListener(new OnMarkerClickListener() {
			
			@Override
			public boolean onMarkerClick(Marker marker) {
				int i = 0;
				LatLng latlng = marker.getPosition();
				String lat = latlng.latitude + "";
				String lon = latlng.longitude + "";
				
				while(!(lat.equals(result.get(i).get(TAG_LatPoint)) && lon.equals(result.get(i).get(TAG_LongPoint))) && i < result.size() - 1){
					i++;
				}
				Id = marker.getTitle();
				topicFormAddWaterLeak = result.get(i).get(TAG_Topic);
				detailFormAddWaterLeak = result.get(i).get(TAG_Detail);
				timeFormAddWaterLeak = result.get(i).get(TAG_Date);
				statusFormAddWaterLeak = result.get(i).get(TAG_Status);
				urlFormAddWaterLeak = result.get(i).get(TAG_Url);
				location = latlng.latitude + " " + latlng.longitude;
				return false;
			}
		});
		
		map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
			
			@Override
			public void onInfoWindowClick(Marker arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			flagAutan = extras.getString("flag");

			if (flagAutan.equals("0")) {
				latitudeFormAddWaterLeak = extras.getString("latitude");
				longtitudeFormAddWaterLeak = extras.getString("longtitude");
				topicFormAddWaterLeak = extras.getString("topic");
				detailFormAddWaterLeak = extras.getString("detail");
				timeFormAddWaterLeak = extras.getString("time");

				LatLng latLng = new LatLng(
						Double.parseDouble(latitudeFormAddWaterLeak),
						Double.parseDouble(longtitudeFormAddWaterLeak));

				Context context = getApplicationContext();
				CharSequence text = "Maker Point!";
				int duration = Toast.LENGTH_LONG;

				Toast toast = Toast.makeText(context, text, duration);
				toast.show();

				markerPoints.add(latLng);

				MarkerOptions markerOptions = new MarkerOptions();
				markerOptions.position(latLng);

				if (markerPoints.size() == 1) {
					markerOptions.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED));
				}

				CameraPosition cameraPosition = new CameraPosition.Builder()
						.target(latLng).zoom(13).bearing(-30).tilt(90).build();

				// map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
				map.animateCamera(CameraUpdateFactory
						.newCameraPosition(cameraPosition));

				// Adding marker on the GoogleMap
				Marker marker = map.addMarker(markerOptions);

				// Showing InfoWindow on the GoogleMap
				marker.showInfoWindow();

			}
		}

		map.setOnMapLongClickListener(new OnMapLongClickListener() {

			@Override
			public void onMapLongClick(LatLng latLng) {

				Intent addMarkWater = new Intent(Detectivemap.this,
						AddWaterLeak.class);
				addMarkWater.putExtra("latitude", latLng.latitude + "");
				addMarkWater.putExtra("longtitude", latLng.longitude + "");

				startActivity(addMarkWater);

			}
		});
	}

	private void setUpMapIfNeeded() {
		if (map == null) {
			map = ((MapFragment) getFragmentManager()
					.findFragmentById(R.id.map)).getMap();

			if (map != null) {
				setUpMap();
			}
		}
	}

	private void setUpMap() {
		map.setMyLocationEnabled(true);
		map.getUiSettings().setCompassEnabled(true);
		map.getUiSettings().setRotateGesturesEnabled(true);
		map.setTrafficEnabled(false);

		url = MainConfiguration.addWaterLeakUrl;
		result = new ArrayList<HashMap<String, String>>();
		// url="http://202.21.149.53/Gecko/api/waterleak/";

		// Getting JSON from URL
		JSONParser jParser = new JSONParser();
		JSONObject json = jParser.getJSONFromUrl(url);
		Log.d("Return JSON: ", json.toString());
		try {
			JSONArray jArray = json.getJSONArray("Data");
			for (int i = 0; i < jArray.length(); i++) {

				HashMap<String, String> map = new HashMap<String, String>();
				JSONObject json_data = jArray.getJSONObject(i);
				map.put(TAG_ID, json_data.getString("Id"));
				map.put(TAG_LatPoint, json_data.getString("LatPoint"));
				map.put(TAG_LongPoint, json_data.getString("LongPoint"));
				map.put(TAG_Status, json_data.getString("Status"));
				map.put(TAG_UserId, json_data.getString("UserId"));
				map.put(TAG_Topic, json_data.getString("Topic"));
				map.put(TAG_Detail, json_data.getString("Detail"));
				map.put(TAG_Date, json_data.getString("Date"));
				map.put(TAG_State, json_data.getString("State"));
				map.put(TAG_Url, json_data.getString("Url"));
				
				result.add(map);
				
				Log.d("Url : ", result.get(i).get(TAG_Url));
				
			}
		}

		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
	}

	private void setUpMarker() {
		LatLng latlng;
		double latitude;
		double longtitude;
		int id;
		for (int index = 0; index < result.size(); index++) {
			id = Integer.parseInt(result.get(index).get(TAG_ID));
			latitude = Double.parseDouble(result.get(index).get(TAG_LatPoint));
			longtitude = Double.parseDouble(result.get(index)
					.get(TAG_LongPoint));
			latlng = new LatLng(latitude, longtitude);
			
			Log.d("Add Marker : ", latitude + " " + longtitude);
			MarkerOptions markerOptions = new MarkerOptions();
			markerOptions.position(latlng).title(id+"");
			
			if ((result.get(index).get(TAG_State)).equals("Close")) {
				markerOptions.icon(BitmapDescriptorFactory
						.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
			}else {
				markerOptions.icon(BitmapDescriptorFactory
						.defaultMarker(BitmapDescriptorFactory.HUE_RED));
			}

			map.addMarker(markerOptions);

		}
	}

	private void setUpBounds() {

		final View mapView = getFragmentManager().findFragmentById(R.id.map)
				.getView();
		if (mapView.getViewTreeObserver().isAlive()) {
			mapView.getViewTreeObserver().addOnGlobalLayoutListener(
					new OnGlobalLayoutListener() {
						@Override
						public void onGlobalLayout() {
							// TODO Auto-generated method stub
							LatLng latlng;
							double latitude;
							double longtitude;
							LatLngBounds.Builder bld = new LatLngBounds.Builder();
							for (int index = 0; index < result.size(); index++) {
								latitude = Double.parseDouble(result.get(index)
										.get(TAG_LatPoint));
								longtitude = Double.parseDouble(result.get(
										index).get(TAG_LongPoint));
								latlng = new LatLng(latitude, longtitude);
								bld.include(latlng);
								Log.d("Setup Bounds : ", latitude + " "
										+ longtitude);

							}
							LatLngBounds bounds = bld.build();
							map.moveCamera(CameraUpdateFactory.newLatLngBounds(
									bounds, 100));
						}
					});
		}
	}

	private void setUpLocation() {

		// Getting Google Play availability status
		int status = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getBaseContext());

		// Showing status
		if (status != ConnectionResult.SUCCESS) { // Google Play Services are
													// not available
			int requestCode = 10;
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
					requestCode);
			dialog.show();

		} else { // Google Play Services are available

			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location
			Location location = locationManager.getLastKnownLocation(provider);
			setLocationPresent(location);
			if (location == null) {
				// onLocationChanged(location);
				locationManager.requestLocationUpdates(provider, 0, 1, this);
				// set location Present
			}

		}
	}

	private long lastPressedTime;
	private static final int PERIOD = 2000;

	private void logOutProcess() throws NotFoundException {
		new AlertDialog.Builder(this)
				.setTitle("LogOut")
				.setMessage("Do you want to logout?")
				.setIcon(
						getResources().getDrawable(
								android.R.drawable.ic_dialog_alert))
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// Do Something Here
								Session session = Session.getActiveSession();
								if (!session.isClosed()) {
									session.closeAndClearTokenInformation();
									Toast.makeText(getApplicationContext(),
											"LogOut Click", Toast.LENGTH_SHORT)
											.show();
									Intent resultData = new Intent();
									resultData.putExtra("LogOut", true);
									setResult(Activity.RESULT_OK, resultData);
									finish();
								}
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// Do Something Here
					}
				}).show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			switch (event.getAction()) {
			case KeyEvent.ACTION_DOWN:
				if (event.getDownTime() - lastPressedTime < PERIOD) {
					finish();
				} else {
					Toast.makeText(getApplicationContext(),
							"Press Back again to quit", Toast.LENGTH_SHORT)
							.show();
					lastPressedTime = event.getEventTime();
				}
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_logout:
			logOutProcess();

		case R.id._clear:
			map.clear();
			// tvDistance.setText("");
			markerPoints.clear();
			break;
		case R.id._normal:
			map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			break;
		case R.id._satellite:
			map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			break;
		case R.id._hybrid:
			map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detectivemap, menu);
		// getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TextView tvLocation = (TextView) findViewById(R.id.tv_location);

		// Getting latitude
		double latitude = location.getLatitude();

		// Getting longitude
		double longitude = location.getLongitude();

		// Creating a LatLng object for the current location
		LatLng latLng = new LatLng(latitude, longitude);

		setLocationPresent(location);

		// Showing the current location in Google Map
		map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

		// Zoom in the Google Map
		map.animateCamera(CameraUpdateFactory.zoomTo(15));

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	public void nextpage(View view) {
		Intent mapIntent = new Intent(getApplicationContext(),
				DetectShortpath.class);
		mapIntent.putExtra("latitudePosition", getLocationPresent()
				.getLatitude() + "");
		mapIntent.putExtra("longtitudePosition", getLocationPresent()
				.getLongitude() + "");
		startActivity(mapIntent);
	}

	public String getDistance() {
		return distance;
	}

	public void setDistance(String distance) {
		this.distance = distance;
	}

	public String getDuration() {
		return duration;
	}

	public void setDuration(String duration) {
		this.duration = duration;
	}

	public Location getLocationPresent() {
		return locationPresent;
	}

	public void setLocationPresent(Location locationPresent) {
		this.locationPresent = locationPresent;
	}


	// public static class EnableGpsDialogFragment extends DialogFragment {
	// @Override
	// public Dialog onCreateDialog(Bundle savedInstanceState) {
	// return new AlertDialog.Builder(getActivity())
	// .setTitle("เธฃเธฐเธ�เธ� GPS")
	// .setMessage("App เธ•เน�เธญเธ�เธ�เธฒเธฃเน�เธ�เน�เธฃเธฐเธ�เธ� Location\nเธ�เธฃเธธเธ“เธฒเน€เธ�เธดเธ” GPS")
	// .setPositiveButton("เน€เธ�เน�เธฒเธ•เธฑเน�เธ�เธ�เน�เธฒเธฃเธฐเธ�เธ�",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// // TODO Auto-generated method stub
	// Intent settingsIntent = new Intent(
	// Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	// }
	// }).create();
	// }
	// }

}